package blue.global.util
{
	import com.hurlant.crypto.Crypto;
	import com.hurlant.crypto.hash.IHash;
	import com.hurlant.crypto.symmetric.ICipher;
	import com.hurlant.crypto.symmetric.IPad;
	import com.hurlant.crypto.symmetric.NullPad;
	import com.hurlant.util.Base64;
	import com.hurlant.util.Hex;
	
	import flash.utils.ByteArray;
	
	/**
	 * 加密工具类
	 */
	public class CryptoUtil
	{
		public function CryptoUtil()
		{
		}
		
		/**
		 * 计算 MD5 值，并返回 Base64 编码
		 */
		public static function getMD5(src : String) : String
		{
			if (src == null || src == "")
				return "";
			
			var hash : IHash = Crypto.getHash("md5");
			var data : ByteArray = Hex.toArray(Hex.fromString(src));
			var raw : ByteArray = hash.hash(data);
			return Base64.encodeByteArray(raw);
		}
		
		/**
		 * 用 MD5 算法判断明文和密文是否相等
		 */
		public static function equalsMD5(src : String, md5 : String) : Boolean
		{
			if (src == null || md5 == null)
				return false;
				
			return getMD5(src) == md5;
		}
		
		/**
		 * 产生一个密钥
		 */
		private static function generateKey(key : String) : ByteArray
		{
			return Hex.toArray(Hex.fromString(key));
		}
		
		/**
		 * 用RC4算法加密字符串
		 */
		public static function encryptRC4(key : String, src: String) : String
		{
			var data : ByteArray = Hex.toArray(Hex.fromString(src));
			var pad : IPad = new NullPad();
			var cipher : ICipher = Crypto.getCipher("rc4", generateKey(key), pad);
			pad.setBlockSize(cipher.getBlockSize());
			cipher.encrypt(data);
			return Base64.encodeByteArray(data);
		}
		
		/**
		 * 用RC4算法解密字符串
		 */
		public static function decryptRC4(key: String, raw : String) : String
		{
			var data : ByteArray = Base64.decodeToByteArray(raw);
			var pad : IPad = new NullPad();
			var cipher : ICipher = Crypto.getCipher("rc4", generateKey(key), pad);
			pad.setBlockSize(cipher.getBlockSize());
			cipher.decrypt(data);
			return Hex.toString(Hex.fromArray(data));
		}
	}
}